package com.ple.app.util;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Environment;

import com.esri.android.map.MapView;
import com.ple.app.jzsf.R;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXImageObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by twenj on 2016/12/29.
 * 获取当前地图视图MapView的截图
 * 将截图保存至SDCard，以及分享至微信
 */

public class GetSnapShot {
    private MapView mapView;
    private String filepath;

    private static final String WECHAT_APP_ID = "wx0f5d77b55fa37f3d";
    private IWXAPI iwxapi;

    public GetSnapShot(Context c,MapView v) {

        //将当前的WECHAT_APP_ID注册到微信
        iwxapi = WXAPIFactory.createWXAPI(c,WECHAT_APP_ID,true);
        iwxapi.registerApp(WECHAT_APP_ID);

        this.mapView = v;
    }

    public String getFilepath() {
        return filepath;
    }

    //获取截图
    public Bitmap getViewBitmap() {
        mapView.clearFocus();
        mapView.setPressed(false);

        boolean willNotCache = mapView.willNotCacheDrawing();
        mapView.setWillNotCacheDrawing(false);
        int color = mapView.getDrawingCacheBackgroundColor();
        mapView.setDrawingCacheBackgroundColor(0);
        if (color != 0) {
            mapView.destroyDrawingCache();
        }
        mapView.buildDrawingCache();
        Bitmap cacheBitmap = null;
        while (cacheBitmap == null) {
            cacheBitmap = mapView.getDrawingMapCache(0, 0, mapView.getWidth(), mapView.getHeight());
        }
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

        //Restore the view
        mapView.destroyDrawingCache();
        mapView.setWillNotCacheDrawing(willNotCache);
        mapView.setDrawingCacheBackgroundColor(color);

        //return the bitmap
        return bitmap;
    }

    //保存截图到SD卡上面
    public void saveViewShotToNative() {
        //set the file name of snapshot
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_hhmmss");
        String timeStr = dateFormat.format(date);
        String path = "arcgis/screenshot";
        String extraPath = Environment.getExternalStorageDirectory().toString();
        String filename = extraPath + "/" + path + "/" + timeStr;

        File file = new File(extraPath + "/" + path);
        if (!file.exists()) {
            System.out.println("path 文件夹 不存在--开始创建");
            file.mkdirs();
            System.out.println(file.exists());
        }

        filename = getFilePath(filename);//判断是否一次多次截图，否则改名
        filepath = filename;
        //存储到SD卡上
        System.out.println("获得的filename--"+filename);
        Bitmap bitmap = getViewBitmap();

        File file1 = new File(filename);
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file1);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //判断是否在一次内多次截图，设定文件名
    private String getFilePath(String filename) {
        String fileStr = filename + ".png";
        File f = new File(fileStr);
        if (f.exists()) {
            filename = getFilePath(filename + "_1");
        } else {
            filename = fileStr;
        }
        return filename;
    }

    //分享地图截图到微信
    public void shareViewToWeChat(){
        //拿到地图截图
        Bitmap bitmap = getViewBitmap();
        bitmap.getByteCount();

        //初始化WXImageObject 和WXMediaMessage对象
        WXImageObject imageObject = new WXImageObject(bitmap);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imageObject;

        //设置缩略图
        Bitmap thumpBMP = Bitmap.createScaledBitmap(bitmap,100,100,true);
        bitmap.recycle();
        msg.thumbData = bmpToByteArray(thumpBMP,true);

        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("ImageShareAppData");
        req.message = msg;
        //req.scene = SendMessageToWX.Req.WXSceneTimeline;//分享至微信
        req.scene = SendMessageToWX.Req.WXSceneSession;//分享至回话
        //req.scene = SendMessageToWX.Req.WXSceneFavorite;//分享到收藏


        //调用API借口发送数据到微信
        boolean a  = iwxapi.sendReq(req);

    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
}
